<?php

namespace App\Http\Controllers\ZHIHU\Topics;

use DB;
use Config;
use Carbon\Carbon;
use App\Http\Controllers\ZHIHU\ApiController;
use Illuminate\Http\Request;
use App\Eloqumd\Zhihu\ZhihuFollower;
use App\Eloqumd\Zhihu\ZhihuFollowerQuestion;
use App\Eloqumd\Zhihu\ZhihuFavouriteQuestion;
use App\Eloqumd\Zhihu\ZhihuReportQuestion;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Validate\Zhihu\ZhihuValidator;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuCollection;
use App\Eloqumd\Zhihu\ZhihuTopic;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuAnswer;
use App\Jobs\SystemMessagePublishedNotify;

class FollowerController extends ApiController
{
    // 关注用户
    public function followerUser(Request $request)
    {
        // 被关注用户ID
        $user_id = $request->input('user_id', 0);
        if (!$user_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 判断是否是重新关注
            if (
                $model = ZhihuFollower::where('follower_id', $this->apiUser['id'])
                    ->where('user_id', $user_id)
                    // ->where('status', 0)
                    ->first()
            ) {
                $model->status = 1;
                $model->updated_at = Carbon::now();
            } else {
                $model = new ZhihuFollower;
                $model->created_at = Carbon::now();
            }

            $model->user_id = $user_id;
            $model->follower_id = $this->apiUser['id'];
            $model->save();

            DB::commit();

            // 消息通知，以及socket
            $msg = new ZhihuMessage;
            $msg->from_id = $this->apiUser['systemId'];
            $msg->from_name = $this->apiUser['systemName'];
            $msg->to_id = (int)$user_id;
            $msg->content = trans('zhihu.Follower-User-Notify', [
                'name' => $this->apiUser['nickname']
            ]);
            $msg->status = 0;
            $msg->is_system = 1;
            $msg->created_at = Carbon::now();
            $msg->save();

            // socket通知
            $job = (new SystemMessagePublishedNotify([
                'channelType' => 'followers',
                'message' => $msg->content,
                'title' => trans('zhihu.System-Follower-Notify-Title'),
                'data' => $msg->toArray()
            ]));
            $this->dispatch($job);

            return $this->jsonReturns(10000, trans('zhihu.Followers-Success'), null, 'follower');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'follower');
        }
    }

    // 取消关注-可批量取消-可全部取消
    public function followerCancelUser(Request $request)
    {
        $id = $request->input('user_id', '');
        // 是否全部取消标识
        $type = $request->input('type', '');

        DB::beginTransaction();
        try {
            $query = ZhihuFollower::where('follower_id', $this->apiUser['id']);
            $updateData = [
                'status' => 0,
                'updated_at' => Carbon::now()
            ];
            // 非全部取消
            if ($type != 'all') {
                if (!is_array($id)) {
                    $id = explode(',', $id);
                }

                if (!$id) {
                    return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
                }
                $query->whereIn('user_id', $id);
            }

            $query->update($updateData);

            DB::commit();
            return $this->jsonReturns(10000, trans('zhihu.Followers-Cancel-Success'), null, 'followercancel');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'followercancel');
        }
    }

    // 我关注的用户
    public function followerList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 用户ID
        $userId = $request->input('user_id', 0);
        $keyword = $request->input('keyword', '');

        $where = null;
        $where[] = ['flr.status', '=', 1, 'AND'];
        if ($userId) {
            $where[] = ['flr.follower_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['flr.follower_id', '=', $this->apiUser['id'], 'AND'];
        }
        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['usr.nickname', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuFollower::from('zhihu_followers as flr')
            ->leftJoin('zhihu_users as usr', 'flr.user_id', '=', 'usr.id')
            ->where($where)
            ->count();
        $listData = ZhihuFollower::from('zhihu_followers as flr')
            ->select('flr.*', 'usr.nickname', 'usr.avatar')
            ->leftJoin('zhihu_users as usr', 'flr.user_id', '=', 'usr.id')
            ->where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 我的粉丝
    public function followerFanceList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 用户ID
        $userId = $request->input('user_id', 0);
        $keyword = $request->input('keyword', '');

        $where = null;
        $where[] = ['flr.status', '=', 1, 'AND'];
        if ($userId) {
            $where[] = ['flr.user_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['flr.user_id', '=', $this->apiUser['id'], 'AND'];
        }
        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['usr.nickname', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuFollower::from('zhihu_followers as flr')
            ->leftJoin('zhihu_users as usr', 'flr.user_id', '=', 'usr.id')
            ->where($where)
            ->count();
        $listData = ZhihuFollower::from('zhihu_followers as flr')
            ->select('flr.*', 'usr.nickname', 'usr.avatar')
            ->leftJoin('zhihu_users as usr', 'flr.follower_id', '=', 'usr.id')
            ->where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // (取消)关注问题
    public function followersQuestion(Request $request)
    {
        // 被关注问题ID
        $question_id = $request->input('question_id', 0);
        $followers = $request->input('followers', 0);

        if (!$question_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 判断是否是重新关注
            if (
                $model = ZhihuFollowerQuestion::where('question_id', $question_id)
                    ->where('user_id', $this->apiUser['id'])
                    ->first()
            ) {
                $model->status = $followers;
                $model->updated_at = Carbon::now();
            } else {
                $model = new ZhihuFollowerQuestion;
                $model->created_at = Carbon::now();
            }

            $model->question_id = $question_id;
            $model->user_id = $this->apiUser['id'];
            $model->save();

            // 更新到问题关注统计中
            $question = ZhihuQuestion::find($question_id);
            $question->followers_count = $question->followers_count + ($followers == 1 ? 1 : -1);
            $question->save();

            DB::commit();

            // 消息通知，以及socket
            if ($followers == 1) {
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['systemId'];
                $msg->from_name = $this->apiUser['systemName'];
                $msg->to_id = (int)$question->user_id;
                $msg->content = trans('zhihu.Forks-Question-Notify', [
                    'name' => $this->apiUser['nickname'],
                    'title' => $question->title
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'forks',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Forks-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // (取消)喜欢问题
    public function favouriteQuestion(Request $request)
    {
        // 被关注问题ID
        $question_id = $request->input('question_id', 0);
        $favourite = $request->input('favourite', 0);

        if (!$question_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 判断是否是重新喜欢
            if (
                $model = ZhihuFavouriteQuestion::where('question_id', $question_id)
                    ->where('user_id', $this->apiUser['id'])
                    ->first()
            ) {
                $model->status = $favourite;
                $model->updated_at = Carbon::now();
            } else {
                $model = new ZhihuFavouriteQuestion;
                $model->created_at = Carbon::now();
            }

            $model->question_id = $question_id;
            $model->user_id = $this->apiUser['id'];
            $model->save();

            // 更新到问题喜欢统计中
            $question = ZhihuQuestion::find($question_id);
            $question->favourite_count = $question->favourite_count + ($favourite == 1 ? 1 : -1);
            $question->save();

            DB::commit();

            // 消息通知，以及socket
            if ($favourite == 1) {
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['systemId'];
                $msg->from_name = $this->apiUser['systemName'];
                $msg->to_id = (int)$question->user_id;
                $msg->content = trans('zhihu.Favourite-Question-Notify', [
                    'name' => $this->apiUser['nickname'],
                    'title' => $question->title
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'favourites',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Favourite-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // (取消)收藏问题
    public function collectionQuestion(Request $request)
    {
        $question_id = $request->input('question_id', 0);
        $collection = $request->input('collection', 0);

        if (!$question_id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            if (
                $model = ZhihuCollection::where('question_id', $question_id)
                    ->where('user_id', $this->apiUser['id'])
                    ->first()
            ) {
                $model->status = $collection;
                $model->updated_at = Carbon::now();
            } else {
                $model = new ZhihuCollection;
                $model->created_at = Carbon::now();
            }

            $model->question_id = $question_id;
            $model->user_id = $this->apiUser['id'];
            $model->save();

            $question = ZhihuQuestion::find($question_id);

            DB::commit();

            // 消息通知，以及socket
            if ($collection == 1) {
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['systemId'];
                $msg->from_name = $this->apiUser['systemName'];
                $msg->to_id = (int)$question->user_id;
                $msg->content = trans('zhihu.Collection-Question-Notify', [
                    'name' => $this->apiUser['nickname'],
                    'title' => $question->title
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'collections',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Collection-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 举报问题
    public function reportQuestion(Request $request)
    {
        $param = $request->all();
        // 数据校验
        if (true !== $validateRes = ZhihuValidator::reportQuestion($param)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $question = ZhihuQuestion::find($param['question_id']);

            $model = new ZhihuReportQuestion;

            $model->question_id = $param['question_id'];
            $model->question_user_id = $question->user_id;
            $model->question_title = $question->title;
            $model->question_content = $question->content;
            $model->report_user_id = $this->apiUser['id'];
            $model->report_type = join(',', $param['report_type']);
            $model->report_descrption = $param['report_descrption'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, trans('zhihu.Report-Success'), null, 'report');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'report');
        }
    }

    // 我关注的问题
    public function myFollowerQuestionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 用户ID
        $userId = $request->input('user_id', 0);
        $keyword = $request->input('keyword', '');

        $where = null;
        $where[] = ['flr.status', '=', 1, 'AND'];
        if ($userId) {
            $where[] = ['flr.user_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['flr.user_id', '=', $this->apiUser['id'], 'AND'];
        }
        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['qsq.title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuFollowerQuestion::from('zhihu_follower_questions as flr')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->count();
        $listData = ZhihuFollowerQuestion::from('zhihu_follower_questions as flr')
            ->select('flr.id as follower_question_id', 'flr.question_id', 'qsq.*')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 我喜欢的问题
    public function myFavouriteQuestionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 用户ID
        $userId = $request->input('user_id', 0);
        $keyword = $request->input('keyword', '');

        $where = null;
        $where[] = ['flr.status', '=', 1, 'AND'];
        if ($userId) {
            $where[] = ['flr.user_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['flr.user_id', '=', $this->apiUser['id'], 'AND'];
        }
        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['qsq.title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuFavouriteQuestion::from('zhihu_favourite_questions as flr')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->count();
        $listData = ZhihuFavouriteQuestion::from('zhihu_favourite_questions as flr')
            ->select('flr.id as favourite_question_id', 'flr.question_id', 'qsq.*')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 我的收藏
    public function getCollectionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        // 用户ID
        $userId = $request->input('user_id', 0);

        $where = null;
        $where[] = ['clt.status', '=', 1, 'AND'];
        if ($userId) {
            $where[] = ['clt.user_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['clt.user_id', '=', $this->apiUser['id'], 'AND'];
        }

        $where[] = ['qsq.status', '=', 1, 'AND'];
        $where[] = ['qsq.cates', '=', 'blog', 'AND'];

        $totalCount = ZhihuCollection::from('zhihu_collections as clt')
            ->leftJoin('zhihu_questions as qsq', 'clt.question_id', '=', 'qsq.id')
            ->where($where)
            ->count();
        $listData = ZhihuCollection::from('zhihu_collections as clt')
            ->select('clt.created_at as collectionDate', 'qsq.*')
            ->leftJoin('zhihu_questions as qsq', 'clt.question_id', '=', 'qsq.id')
            ->where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
            $listData[$k]['collections'] = (int)ZhihuCollection::where('question_id', $v['id'])->where('status', 1)->count();
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 我评论的问题
    public function myCommentQuestionList(Request $request)
    {
        $page = (int)$request->input('page', 1);
        $limit = $request->input('limit', $this->limit);
        $offest = ($page - 1) * $limit;
        $keyword = $request->input('keyword', '');
        // 用户ID
        $userId = $request->input('user_id', 0);

        $where = null;
        $where[] = ['flr.status', '=', 1, 'AND'];

        if ($userId) {
            $where[] = ['flr.user_id', '=', $userId, 'AND'];
        } else {
            $where[] = ['flr.user_id', '=', $this->apiUser['id'], 'AND'];
        }

        // 快捷搜索-问题标题
        if ($keyword) {
            $where[] = ['qsq.title', 'like', "%{$keyword}%", 'AND'];
        }

        // 有问题 TODO
        $totalCount = ZhihuAnswer::from('zhihu_answers as flr')
            ->select('flr.question_id', 'qsq.*')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->groupBy('flr.question_id')
            ->get()
            ->toArray();
        $totalCount = count($totalCount);
        $listData = ZhihuAnswer::from('zhihu_answers as flr')
            ->select('flr.question_id', 'qsq.*')
            ->leftJoin('zhihu_questions as qsq', 'flr.question_id', '=', 'qsq.id')
            ->where($where)
            ->groupBy('flr.question_id')
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();
        foreach ($listData as $k => $v) {
            $topic = ZhihuTopic::find($v['topic_id']);
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['topic'] = $topic->name;
            $listData[$k]['publishname'] = $user->nickname;
            $listData[$k]['fclr'] = $v['favourite_count'] . ' / ' . $v['answers_count'] . ' / ' . $v['followers_count'] . ' / ' . $v['read_count'];
            $listData[$k]['catesShow'] = Config::get('api.zhihu_question_type')[$v['cates']];
            $listData[$k]['timeShow'] = time_trans($v['created_at']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }
}
